<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>你画我猜</title>
		<script src="../../js/jquery-1.8.3.min.js"></script>
		<link href="../../css/nhwcgame.css" rel="stylesheet" type="text/css" />
		<script type="text/javascript">
	/***********************/
	/* deal with websocket */
	/***********************/
	var GameCanvas = {};
	GameCanvas.socket = null;
	GameCanvas.connect = (function(host) {
		if ('WebSocket' in window) {
			GameCanvas.socket = new WebSocket(host);
		} else if ('MozWebSocket' in window) {
			GameCanvas.socket = new MozWebSocket(host);
		} else {
			Console.log('Error: WebSocket is not supported by this browser.');
			return;
		}
		GameCanvas.socket.onopen = function () {
			Console.log("* 点击准备按钮，等待开始游戏。");
			document.getElementById('chat').onkeydown = function(event) {
				if (event.keyCode == 13) {
					GameCanvas.sendMessage();
				}
			};
		};
		GameCanvas.socket.onclose = function () {
			document.getElementById('chat').onkeydown = null;
			Console.log('Info: WebSocket connection closed.');
		};
		GameCanvas.socket.onmessage = function (message) {
			if(message.data.substring(0,4)!="#@#&"){
				// if the message is not an instruction
				Console.log(message.data);
			}else{			
				// if the message is an instruction
				// the format of message is: "ins_type x y"
				// get the three variables of the instruction
				var msgtmp = message.data.substring(4);
				var indextmp1 = msgtmp.indexOf(" ");
				var indextmp2 = msgtmp.lastIndexOf(" ");
				var instruction = parseInt(msgtmp.substring(0,indextmp1));
				//var ins_x = parseInt(msgtmp.substring(indextmp1+1,indextmp2));
				//var ins_y = parseInt(msgtmp.substring(indextmp2+1));
				var ins_x = msgtmp.substring(indextmp1+1,indextmp2);
				var ins_y = msgtmp.substring(indextmp2+1);
				// call the handleInstruction to deal with the instruction			
				handleInstruction(instruction,ins_x,ins_y);
			}
		};
	});
	GameCanvas.initialize = function() {
		/*function getUrlParam(name) {
			var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
			var r = window.location.search.substr(1).match(reg);  //匹配目标参数
			if (r!=null)
				return unescape(r[2]);
			return null; //返回参数值
		}*/
		//var roomid = getUrlParam('roomid');
		var param;
		//if(roomid!=null){
			param = "?gameid=<s:property value='gameid' />&iduser=<s:property value='iduser' />&nickname=<s:property value='nickname' />";
		//}else{
		//	param = "";
		//}
		if (window.location.protocol == 'http:') {
			GameCanvas.connect('ws://' + window.location.host + '/SNS/NHWCWebSocket.servlet'+param);
		} else {
			GameCanvas.connect('wss://' + window.location.host + '/SNS/NHWCWebSocket.servlet'+param);
		}
	};
	// send the message to chat
	GameCanvas.sendMessage = (function() {
		var message = document.getElementById('chat').value;
		// message should not be empty
		if (message != '') {
			if(message.substring(0,4)=="#@#&"){
				// the message should not begin with #@#&
				document.getElementById('chat').value = "The message should not begin with #@#&";
			}else{
				GameCanvas.socket.send(message);
				document.getElementById('chat').value = '';	
			}
		}
	});
	// send the instruction information
	GameCanvas.sendInstruction = (function(message) {
		GameCanvas.socket.send(message);
	});
	
	// the console in the web page
	var Console = {};
	Console.log = (function(message) {
		var console = document.getElementById('console');
		var p = document.createElement('p');
		p.style.wordWrap = 'break-word';
		p.innerHTML = message;
		console.appendChild(p);
		while (console.childNodes.length > 100) {
			console.removeChild(console.firstChild);
		}
		console.scrollTop = console.scrollHeight;
	});
	// initiallize the GameCanvas
	GameCanvas.initialize();

	/**************************/
	/* deal with html5 canvas */
	/**************************/
	// final constant
	// different types of the instructions
	var MOUSE_DOWN = 0;
	var MOUSE_MOVE = 1;
	var MOUSE_UP = 2;
	var PENCIL = 3;
	var RUBBER = 4;
	var CLEAR_ALL = 5;
	var GAME_INIT = 6;
	var GAME_DRAWER=7;
	var GAME_GUESSER=8;
	var GAME_PREPARE = 9;
	var GAME_ROOM_NUM = 10;
	var GAME_PLAYER_NUM = 11;
	var USERLIST_ADD = 12;
	var USERLIST_REMOVE = 13;
	// different states of the player
	var NOT_PREPARING = 0;
	var PREPARING = 1;
	var DRAWER_NOT_DRAWING = 2;
	var DRAWER_DRAWING = 3;
	var GUESSER_GUESSING = 4;
	// global variables
	var canvas;
	var context;
	var state = NOT_PREPARING;
	var clientOffsetX =153;
	var clientOffsetY =53;
	
	// test if the html page has been loaded
	// when the whole page has been loaded, call the canvasApp
	window.onload = eventWindowLoaded;
	function eventWindowLoaded () {
		canvasApp();
	}
	// initialize the canvas
	function canvasApp(){
		canvas = document.getElementById("myCanvas");
		// test if there exist the element
		if(!canvas){
			return;
		}
		context = canvas.getContext("2d");
		// test if the browser supports canvas
		if(!context){
			return;
		}
		// add listener to the canvas
		canvas.onmousedown=canvasMousedownHandler;
		canvas.onmousemove=canvasMousemoveHandler;
		canvas.onmouseup=canvasMouseupHandler;
		// initialize the context
		context.strokeStyle = "black"; //need list of available colors
		context.lineWidth = 1;
		context.lineCap = 'round'; // square butt round
		context.lineJoin = 'round'; // bevel round miter
	}
	// handle different instructions
	function handleInstruction(instruction,ins_x,ins_y){
		var x = parseInt(ins_x);
		var y = parseInt(ins_y);
		switch(instruction){
		case MOUSE_DOWN:
			context.beginPath();
			context.moveTo(x,y);
			break;
		case MOUSE_MOVE:
			context.lineTo(x,y);
			context.stroke();
			break;
		case MOUSE_UP:
			context.closePath();
			break;
		case PENCIL:
			context.strokeStyle="black";
			context.lineWidth=1;
			break;
		case RUBBER:
			context.strokeStyle="white";
			context.lineWidth=20;
			break;
		case CLEAR_ALL:
			context.clearRect(0,0,600,400);
			break;
		case GAME_DRAWER:
			state=DRAWER_NOT_DRAWING;
			// show up the canvas tools
			var canvasToolLabel=document.getElementById("canvasTool");
			canvasToolLabel.className="";
			break;
		case GAME_GUESSER:
			state=GUESSER_GUESSING;
			Console.log("* 游戏开始");
			break;
		case GAME_INIT:
			newGame();
			break;
		case GAME_ROOM_NUM:
			updateRoomNum(x);
			break;
		case GAME_PLAYER_NUM:
			updatePlayerNum(x,y);
			break;
		case USERLIST_ADD:
			y = ins_y;
			$("#users-div").append("<div id='users-div-"+x+"'><a target='_blank' href='../../gotoMain.action?userId="+x+"'>"+y+"</a></div>");
			break;
		case USERLIST_REMOVE:
			y = ins_y;
			$("#users-div-"+x).remove();
			break;
		}
	}
	
	function getProtocolFormat(ins_type,x,y){
		return "#@#&"+ins_type+" "+x+" "+y;
	}
	
	function updateRoomNum(num){
		var labletmp=document.getElementById("roomNum");
		labletmp.innerHTML=num;
	}
	function updatePlayerNum(num1,num2){
		if(num1>=0){
			var labletmp=document.getElementById("playerNum");
			labletmp.innerHTML=num1;
		}
		if(num2>=0){
			var labletmp=document.getElementById("preparedNum");
			labletmp.innerHTML=num2;
		}
	}
	// initialize a new game
	function newGame(){
		state=NOT_PREPARING;
		var prepareToolLabel = document.getElementById("prepareTool");
		prepareToolLabel.className="";
		var canvasToolLabel=document.getElementById("canvasTool");
		canvasToolLabel.className="offDisplay";
		context.clearRect(0,0,600,400);
		updatePlayerNum(-1,0);
	}
	function canvasMousedownHandler(e){
		// left mouse down
		if(state==DRAWER_NOT_DRAWING&&e.button==0){
			state=DRAWER_DRAWING;
			var x;
			var y;
			if(e.offsetX){
				x=e.offsetX;
				y=e.offsetY;
			}else{// browser does not supprot offsetX
				x=e.clientX-clientOffsetX;
				y=e.clientY-clientOffsetY;
			}
			GameCanvas.sendInstruction(getProtocolFormat(MOUSE_DOWN,x,y));
		}
	}
	function canvasMousemoveHandler(e){
		// left mouse move
		if(state==DRAWER_DRAWING){
			var x;
			var y;
			if(e.offsetX){
				x=e.offsetX;
				y=e.offsetY;
			}else{// browser does not supprot offsetX
				x=e.clientX-clientOffsetX;
				y=e.clientY-clientOffsetY;
			}
			GameCanvas.sendInstruction(getProtocolFormat(MOUSE_MOVE,x,y));
		}
	}
	function canvasMouseupHandler(e){
		// left mouse up
		if(state==DRAWER_DRAWING&&e.button==0){
			state=DRAWER_NOT_DRAWING;
			GameCanvas.sendInstruction(getProtocolFormat(MOUSE_UP,-1,-1));
		}
	}
	// swith to pencil
	function pencilButtonClick(){
		if(state==DRAWER_NOT_DRAWING){
			GameCanvas.sendInstruction(getProtocolFormat(PENCIL,-1,-1));
		}
	}
	// swith to rubber
	function rubberButtonClick(){
		if(state==DRAWER_NOT_DRAWING){
			GameCanvas.sendInstruction(getProtocolFormat(RUBBER,-1,-1));
		}
	}
	// clear all the canvas
	function clearAllButtonClick(){
		if(state==DRAWER_NOT_DRAWING){
			GameCanvas.sendInstruction(getProtocolFormat(CLEAR_ALL,-1,-1));
		}
	}
	// start the game
	function gamePrepareButtonClick(){
		if(state==NOT_PREPARING){
			state=PREPARING;
			var prepareToolLabel = document.getElementById("prepareTool");
			prepareToolLabel.className="offDisplay";
			GameCanvas.sendInstruction(getProtocolFormat(GAME_PREPARE,-1,-1));
		}
	}
	// end the game
	function gameEndButtonClick(){
		if(state==DRAWER_NOT_DRAWING){
			state=NOT_PREPARING;
			GameCanvas.sendInstruction(getProtocolFormat(GAME_INIT,-1,-1));
		}
	}
</script>
	</head>

	<body>
		<noscript>
			<h2 style="color: #ff0000">
				Seems your browser doesn't support Javascript! Please enable
				Javascript and reload this page!
			</h2>
		</noscript>

		<div class="sys-pic" id="head-pic"></div>
		<!-- 定义页面上方浮动栏 -->
		<div id="head-bar">
			<div id="bar-wrap">
				<a href="../../gotoMain.action">
					<div class="sys-pic" id="logo"></div> </a>
				<!-- 使用clear属性清理浮动，下同 -->
				<div class="clear"></div>
			</div>
		</div>

		<div id="gameDiv">
			<div id="gameChat">
				<div id="gameInfo">
					房间号：
					<label id="roomNum">
						0
					</label>
					玩家人数：
					<label id="playerNum">
						0
					</label>
					玩家已准备：
					<label id="preparedNum">
						0
					</label>
				</div>
				<div id="inputText">
					<input type="text" placeholder="type and press enter to chat"
						id="chat"></input>
				</div>
				<div id="console"></div>
			</div>
			<canvas id="myCanvas" width="600" height="400">
			Your browser does not support HTML5 Canvas.
			</canvas>
			<div id="gameTool">
				<div id="canvasTool" class="offDisplay">
					<button onclick="pencilButtonClick()">
						铅笔
					</button>
					<button onclick="rubberButtonClick()">
						橡皮
					</button>
					<button onclick="clearAllButtonClick()">
						清空
					</button>
					<button onclick="gameEndButtonClick()">
						结束
					</button>
				</div>
				<div id="prepareTool" class="offDisplay">
					<button onclick="gamePrepareButtonClick()">
						准备
					</button>
				</div>
			</div>
		</div>
		<div id="users-div">
			<div>
				玩家列表：
			</div>
		</div>
	</body>
</html>
